package com.pf.java.ThreadTest;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoinPool
 *
 * ClassName:Thread14
 * Package:com.pf.java.ThreadTest
 *
 * @author: pf
 * @date: 2021/11/22-16:08
 */
public class Thread14 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int[] nums = new int[100];
        for (int i = 1; i <= 100; i++) {
            nums[i-1] = i;
        }

        ForkJoinPool pool = new ForkJoinPool();
        Future<Integer> future = pool.submit(new FJTask(nums, 0, nums.length - 1));
        System.out.println(future.get());
    }

    private static class FJTask extends RecursiveTask<Integer> {

        private static final int THRESHOLD = 10;//阀值
        private int[] nums;
        private int start, end;

        public FJTask(int[] nums, int start, int end) {
            this.nums = nums;
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            System.out.printf("%-25s\t%2d,%2d\n", Thread.currentThread().getName(), start, end);

            Integer sum = 0;

            if (end - start < THRESHOLD) {
                for (int i = start; i <= end; i++) {
                    sum +=nums[i];

                }
            } else {
                int middle = (start + end) / 2;
                FJTask left = new FJTask(nums, start, middle);
                FJTask right = new FJTask(nums, middle + 1, end);
                left.fork();
                right.fork();
                sum = left.join() + right.join();
            }

            return sum;
        }
    }


}
